<template>
  <div class="payment-qr-code-container">
    <div class="payment-header">
      <h3>请使用手机扫码支付</h3>
      <p class="payment-tip">请在 {{ remainingTime }} 秒内完成支付</p>
    </div>
    
    <div class="qr-code-wrapper">
      <img :src="paymentUrl" alt="支付二维码" class="qr-code" v-if="paymentUrl" />
      <div class="loading" v-else>
        <el-icon><Loading /></el-icon>
        <span>生成支付二维码中...</span>
      </div>
    </div>
    
    <div class="payment-info">
      <p>支付金额：¥{{ amount.toFixed(2) }}</p>
      <p>支付方式：{{ getPaymentMethodName(paymentMethod) }}</p>
      <p v-if="statusMessage" class="status-message" :class="statusClass">
        {{ statusMessage }}
      </p>
    </div>
    
    <div class="payment-actions">
      <el-button type="primary" @click="refreshPayment" :loading="refreshing">
        刷新二维码
      </el-button>
      <el-button type="success" @click="queryPaymentStatus" :loading="querying">
        查询支付状态
      </el-button>
      <el-button @click="$emit('cancel')">
        取消支付
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ElIcon, ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import { checkPaymentStatus } from '@/api/account/account';

// Props
interface Props {
  // 移除expireTime属性，因为我们可以在组件内部计算
  rechargeNo: string; // 充值单号是必需的
  amount: number;
  paymentMethod: string;
}

const props = withDefaults(defineProps<Props>(), {});

// Emits
const emit = defineEmits<{
  cancel: [];
  refresh: [];
  paymentSuccess: [];
}>();

// States
const remainingTime = ref(90 * 60); // 默认90分钟倒计时
const refreshing = ref(false);
const querying = ref(false);
const statusMessage = ref('');
const statusClass = ref('');
let countdownTimer: NodeJS.Timeout | null = null;

// 计算二维码图片的URL
const paymentUrl = computed(() => {
  if (!props.rechargeNo) return '';
  // 直接使用后端接口作为图片源
  return `/api/pay?rechargeNo=${props.rechargeNo}`;
});

// Computed
const getPaymentMethodName = (method: string): string => {
  const methods: Record<string, string> = {
    'ALIPAY': '支付宝',
    'WECHAT': '微信支付'
  };
  return methods[method] || method;
};

// Methods
const refreshPayment = async () => {
  refreshing.value = true;
  try {
    // 由于直接使用URL作为图片源，刷新时只需要重新设置remainingTime
    remainingTime.value = 90 * 60;
    startCountdown();
    await new Promise(resolve => setTimeout(resolve, 500));
  } catch (error) {
    ElMessage.error('刷新二维码失败，请重试');
  } finally {
    refreshing.value = false;
  }
};

const queryPaymentStatus = async () => {
  if (!props.rechargeNo) {
    ElMessage.warning('充值单号不存在，无法查询');
    return;
  }
  
  querying.value = true;
  statusMessage.value = '';
  
  try {
    const result = await checkPaymentStatus(props.rechargeNo);
    
    // 适配R类返回格式
    if (result.success) {
      statusMessage.value = result.message;
      
      if (result.data?.status === 'SUCCESS') {
        statusClass.value = 'success';
        ElMessage.success('支付成功！');
        emit('paymentSuccess');
        if (countdownTimer) {
          clearInterval(countdownTimer);
        }
      } else if (result.data?.status === 'PENDING') {
        statusClass.value = 'pending';
        ElMessage.info('支付尚未完成，请稍后再查');
      }
    } else {
      statusMessage.value = result.message || '查询失败';
      statusClass.value = 'error';
      ElMessage.error('查询支付状态失败');
    }
  } catch (error) {
    statusMessage.value = '查询异常，请稍后重试';
    statusClass.value = 'error';
    ElMessage.error('网络异常，请稍后重试');
  } finally {
    querying.value = false;
  }
};

const startCountdown = () => {
  // 清除之前的定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  // 设置新的定时器
  countdownTimer = setInterval(() => {
    remainingTime.value -= 1;
    if (remainingTime.value <= 0) {
      clearInterval(countdownTimer!);
      ElMessage.warning('二维码已过期，请刷新');
    }
  }, 1000);
};

// Lifecycle
onMounted(() => {
  startCountdown();
  
  // 自动检查支付状态（每5秒一次）
  const autoCheckTimer = setInterval(() => {
    if (!querying.value) {
      queryPaymentStatus();
    }
  }, 5000);
  
  // 保存定时器以便组件销毁时清除
  countdownTimer = autoCheckTimer as unknown as NodeJS.Timeout;
});

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style scoped>
.payment-qr-code-container {
  padding: 20px;
  text-align: center;
}

.payment-header {
  margin-bottom: 30px;
}

.payment-header h3 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 10px;
}

.payment-tip {
  color: #606266;
  font-size: 14px;
}

.qr-code-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 240px;
  height: 240px;
  margin: 0 auto 30px;
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.qr-code {
  width: 200px;
  height: 200px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading span {
  margin-top: 10px;
  color: #606266;
}

.payment-info {
  margin-bottom: 30px;
}

.payment-info p {
  color: #303133;
  font-size: 16px;
  margin-bottom: 8px;
}

.status-message {
  font-weight: bold;
  padding: 10px;
  border-radius: 4px;
  margin-top: 15px;
}

.status-message.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-message.pending {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-message.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
}
</style>